package com.qiusuo0226.platform.interceptor;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.qiusuo0226.http.util.HttpServletRequestTool;
import com.qiusuo0226.mvc.util.JsonResultModel;
import com.qiusuo0226.security.config.SecurityProperty;
import com.qiusuo0226.security.util.JWTTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 拦截器
 * @author qiusuo
 * @date 2023/6/19 16:40
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private SecurityProperty securityProperty;

    /**
     * 处理请求之前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // token校验
        try {
            // 取出请求头中Authorization的信息，就是token内容，接下来就是各种判断
            String token = request.getHeader("Authorization");
            // jwt校验
            JSONObject verify = JWTTool.verify(token, securityProperty.getJwtKey());
            // token生成IP
            String tokenIp = verify.getStr("ip");
            // 获取当前请求的IP
            String remoteHost = HttpServletRequestTool.getRemoteHost(request);
            boolean ipCheck = StringUtils.equals(tokenIp, remoteHost);

            // 如果生成token的IP和当前请求的IP不一致
            if (!ipCheck) {
                // 做异常返回
                returnJson(response, JsonResultModel.tokenCrossBorderError());
                return false;
            }

        } catch (Exception e) {
            log.error("token检验异常", e);
            // 做异常返回
            returnJson(response, JsonResultModel.tokenError());
            return false;
        }
        return true;
    }

    private void returnJson(HttpServletResponse response, JsonResultModel result){
        PrintWriter writer = null;
        response.setCharacterEncoding(Consts.UTF_8.name());
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e){
            log.error("拦截器输出流异常", e);
        } finally {
            if(writer != null) {
                writer.close();
            }
        }
    }

    /**
     * 处理请求之后执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        MDC.clear();
    }



}
